package com.zjeav.lingjiao.ui.personCenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dalimao.corelibrary.pullrefresh.BGANormalRefreshViewHolder;
import com.dalimao.corelibrary.pullrefresh.BGARefreshLayout;
import com.dalimao.corelibrary.pullrefresh.PowerfulRecyclerView;
import com.dalimao.corelibrary.pullrefresh.TipView;
import com.dalimao.corelibrary.swipeback.SwipeBackActivity;
import com.dalimao.corelibrary.utils.NetWorkUtils;
import com.dalimao.corelibrary.view.SelfDialog;
import com.maning.mndialoglibrary.MProgressDialog;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.FavorriteBookAdapter;
import com.zjeav.lingjiao.base.baseBean.BaseApplication;
import com.zjeav.lingjiao.base.baseBean.Metadata;
import com.zjeav.lingjiao.base.comon.CommonPersenter;
import com.zjeav.lingjiao.base.comon.CommonView;
import com.zjeav.lingjiao.base.response.AccessToken;
import com.zjeav.lingjiao.base.tools.FileUtils;
import com.zjeav.lingjiao.base.tools.LocalUtils;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.base.utils.ErrorUtils;
import com.zjeav.lingjiao.base.utils.NetworkUtils;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.book.BookDetialActivity;
import com.zjeav.lingjiao.ui.music.MusicActivity;
import com.zjeav.lingjiao.ui.music.MusicService;
import com.zjeav.lingjiao.ui.personCenter.view.PersonInfoContract;

import org.xutils.DbManager;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import okhttp3.ResponseBody;

import static com.zjeav.lingjiao.base.tools.SystemTools.isServiceRunning;

public class MyFavoriteActivity extends SwipeBackActivity implements PersonInfoContract.FavoriteView,
         BGARefreshLayout.BGARefreshLayoutDelegate,CommonView.View {

    private TipView tipView;
    private BGARefreshLayout mRefreshLayout;
    private PowerfulRecyclerView mFavorites;

    private PersonPresenter personPresenter;
    private FavorriteBookAdapter adapter;
    private boolean ispull = true; //是否是下拉刷新
    private DbManager db;
    private ArrayList<Metadata> metadatas = new ArrayList<>();
    private SelfDialog selfDialog;
    private ResponseBody downBody, downBody2;
    private int loadCount = 0;
    private String metaName, lrcName;
    private CommonPersenter commonPersenter;
    Metadata localMetadata;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_download_layout);
        init();
    }

    private void init() {
        db = BaseApplication.dbManager;
        tipView = findViewById(R.id.tip_view);
        mRefreshLayout = findViewById(R.id.refresh_layout);
        mFavorites = findViewById(R.id.rv_favorites);
        commonPersenter = new CommonPersenter(this);
        adapter = new FavorriteBookAdapter(this);
        adapter.setEnableLoadMore(true);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                localMetadata = (Metadata) adapter.getItem(position);
                metaName = localMetadata.getTitle() + ".mp3";
                lrcName = localMetadata.getTitle() + ".lrc";
                boolean isLoad=false;
                int posi=0;
                boolean is4G = (boolean) SharedPreferencesUtils.getParam(MyFavoriteActivity.this, "is4G", false);
                int netType = NetworkUtils.getNetWorkType(MyFavoriteActivity.this);
                MusicActivity.mp3Infos = LocalUtils.getList(db,localMetadata.getBookid());
                if (MusicActivity.mp3Infos!=null){
                    for (int i=0;i<MusicActivity.mp3Infos.size();i++){
                        if (localMetadata.getId()==MusicActivity.mp3Infos.get(i).getId()){
                            isLoad=true;
                            if (FileUtils.fileisDownload(MusicActivity.mp3Infos.get(i).getUrl()) && FileUtils.fileisDownload(MusicActivity.mp3Infos.get(i).getSrturl())){
                                posi = i;
                                int currentTime=(int) SharedPreferencesUtils.getParam(getApplicationContext(),"currentTime",0);

                                if (isServiceRunning(getBaseContext(), "com.zjeav.lingjiao.ui.music.MusicService")) {
                                    stopService(new Intent(MyFavoriteActivity.this, MusicService.class));
                                }else {
                                    SharedPreferencesUtils.setParam(MyFavoriteActivity.this,"currentTime",0);
                                }
                                Intent musicintent = new Intent(MyFavoriteActivity.this, MusicActivity.class);
                                //当前播放的位置
                                musicintent.putExtra("position", String.valueOf(i));
                                musicintent.putExtra("currentTime",currentTime);
                                musicintent.putExtra("type", 1);

                                //启动音乐播放界面
                                startActivity(musicintent);
                            }else {
                                LocalUtils.deleItem(db,localMetadata.getId());
                                if (netType != 1) {
                                    if (!is4G) {
                                        showDiagle();
                                    } else {
                                        MProgressDialog.showProgress(MyFavoriteActivity.this, "下载中...");
                                        commonPersenter.downLoad(localMetadata.getUrl(), 1);
                                        commonPersenter.downLoad(localMetadata.getSrturl(), 2);
                                    }

                                } else {
                                    MProgressDialog.showProgress(MyFavoriteActivity.this, "下载中...");
                                    commonPersenter.downLoad(localMetadata.getUrl(), 1);
                                    commonPersenter.downLoad(localMetadata.getSrturl(), 2);
                                }
                            }
                        }
                    }
                }
                if (!isLoad){
                    if (netType != 1) {
                        if (!is4G) {
                            showDiagle();
                        } else {
                            MProgressDialog.showProgress(MyFavoriteActivity.this, "下载中...");
                            commonPersenter.downLoad(localMetadata.getUrl(), 1);
                            commonPersenter.downLoad(localMetadata.getSrturl(), 2);
                        }

                    } else {
                        MProgressDialog.showProgress(MyFavoriteActivity.this, "下载中...");
                        commonPersenter.downLoad(localMetadata.getUrl(), 1);
                        commonPersenter.downLoad(localMetadata.getSrturl(), 2);
                    }
                }

            }
        });
        mRefreshLayout.setDelegate(this);
        mFavorites.setLayoutManager(new GridLayoutManager(this, 1));
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, false);
        // 设置下拉刷新
        refreshViewHolder.setRefreshViewBackgroundColorRes(R.color.color_F3F5F4);//背景色
        refreshViewHolder.setPullDownRefreshText(UIUtils.getString(R.string.refresh_pull_down_text));//下拉的提示文字
        refreshViewHolder.setReleaseRefreshText(UIUtils.getString(R.string.refresh_release_text));//松开的提示文字
        refreshViewHolder.setRefreshingText(UIUtils.getString(R.string.refresh_ing_text));//刷新中的提示文字
        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
        mRefreshLayout.shouldHandleRecyclerViewLoadingMore(mFavorites);
        mFavorites.setAdapter(adapter);

        personPresenter = new PersonPresenter(this);
        personPresenter.getFavorites();
    }
    private void showDiagle() {
        selfDialog = new SelfDialog(this);
        selfDialog.setTitle("提示");
        selfDialog.setMessage("当前网络不是WIFI状态，是否继续下载?");
        selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                selfDialog.dismiss();
                MProgressDialog.showProgress(MyFavoriteActivity.this, "下载中...");
                commonPersenter.downLoad(localMetadata.getUrl(), 1);
                commonPersenter.downLoad(localMetadata.getSrturl(), 2);

            }
        });
        selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                selfDialog.dismiss();
            }
        });
        selfDialog.show();
    }
    private  MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private WeakReference<MyFavoriteActivity> mActivity;

        public MyHandler(MyFavoriteActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mActivity.get().loadCount++;
                    if (mActivity.get().loadCount == 2) {
                        mActivity.get().loadCount = 0;
                        MProgressDialog.dismissProgress();
                        Toast.makeText(mActivity.get(), "下载完成", Toast.LENGTH_SHORT).show();

//                        mActivity.get().adapter.setNewData(null);
//                        mActivity.get().adapter.setNewData(mActivity.get().newData);
                        LocalUtils.SaveMete(mActivity.get().db, mActivity.get().localMetadata, mActivity.get().metaName, mActivity.get().lrcName,mActivity.get().localMetadata.getBookid());
                        MusicActivity.mp3Infos = LocalUtils.getList(mActivity.get().db,mActivity.get().localMetadata.getBookid());
                        if (isServiceRunning(mActivity.get().getApplicationContext(), "com.zjeav.lingjiao.ui.music.MusicService")) {
                            mActivity.get().stopService(new Intent(mActivity.get().getApplicationContext(), MusicService.class));
                        }else {
                            SharedPreferencesUtils.setParam(mActivity.get().getApplicationContext(),"currentTime",0);
                        }
                        for (int i = 0; i < MusicActivity.mp3Infos.size(); i++) {
                            if (MusicActivity.mp3Infos.get(i).getId() == mActivity.get().localMetadata.getId()) {
                                int currentTime=(int) SharedPreferencesUtils.getParam(mActivity.get().getApplicationContext(),"currentTime",0);
                                Intent musicintent = new Intent(mActivity.get(), MusicActivity.class);
                                //当前播放的位置
                                musicintent.putExtra("position", String.valueOf(i));
                                musicintent.putExtra("type", 1);
                                musicintent.putExtra("currentTime",currentTime);
                                //启动音乐播放界面
                                mActivity.get().startActivity(musicintent);
                            }
                        }
                    }
                    break;
            }
        }
    }

    Runnable networkTask1 = new Runnable() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 0;
            myHandler.sendMessage(message);
            FileUtils.writeResponseBodyToDisk(MyFavoriteActivity.this, downBody, metaName, myHandler);
        }
    };
    Runnable networkTask2 = new Runnable() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 0;
            myHandler.sendMessage(message);
            FileUtils.writeResponseBodyToDisk(MyFavoriteActivity.this, downBody2, lrcName, myHandler);
        }
    };
    @Override
    public void showFavorites(ArrayList<Metadata> books) {

        if (ispull) {
            tipView.show("加载数据成功");
        }

        if (books.size()<= 0) {
            adapter.loadMoreEnd();
            mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
            tipView.show("暂无数据");
            return;
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
        this.metadatas.addAll(books);
        adapter.replaceData(this.metadatas);
    }

    @Override
    public void getLoadResult(ResponseBody body, int type) {
        if (type == 1) {
            downBody = body;
            new Thread(networkTask1).start();
        } else {
            downBody2 = body;
            new Thread(networkTask2).start();
        }

    }

    @Override
    public void getAccessToken(AccessToken token) {

    }

    @Override
    public void showError(Throwable throwable) {
        Toast.makeText(this, ErrorUtils.showError(throwable), Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        ispull =true;
        if (!NetWorkUtils.isNetworkAvailable(this)) {
            //网络不可用弹出提示
            tipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }

        metadatas.clear();
        personPresenter.getFavorites();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }
}
